package com.gitee.wsl.android.store.preferences

import android.annotation.SuppressLint
import android.content.SharedPreferences
import com.gitee.wsl.data.store.AbstractStoreServer
import com.gitee.wsl.data.store.StateSavedVar
import kotlin.reflect.KClass


class PreferencesStoreServer(val preferences: SharedPreferences): AbstractStoreServer() {

    override fun <T : Any> getOrNull(key: String, type: KClass<T>): T? {
        //if(type == null) throw IllegalArgumentException("This type can be get from Preferences")
        val value:Any = when(type){
            Long::class -> preferences.getLong(key,0)
            String::class -> preferences.getString(key, "")?:""
            Int::class -> preferences.getInt(key, 0)
            Boolean::class -> preferences.getBoolean(key, false)
            Float::class -> preferences.getFloat(key, 0f)
//            else -> {
//                return getExtPreference(name, type)
//            }
            else -> {}
        }
        return value as T
    }


    @SuppressLint("CommitPrefEdits")
    override fun <T : Any> realPut(key: String, value: T){
        with(preferences.edit()) {
            when (value) {
                is Long -> putLong(key, value)
                is Int -> putInt(key, value)
                is String -> putString(key, value)
                is Boolean -> putBoolean(key, value)
                is Float -> putFloat(key, value)
                else -> {
//              val str = serialExtPreference(value)
//              putString(name,str)
                }
            }
        }.apply{}
    }

    @SuppressLint("CommitPrefEdits")
    override fun realRemove(key: String)  {
        with( preferences.edit()) {
            remove(key)
        }
    }

    override fun isExits(key: String): Boolean {
        return preferences.contains(key)
    }
}

fun <T : Any> SharedPreferences.saveAble(key:String, defaultValue:T): StateSavedVar<T> = StateSavedVar(
    PreferencesStoreServer(this),key, defaultValue)



//fun <T> SharedPreferences.saveNullAble(key:String,type: T): StateSavedNullAbleVar<T> = StateSavedNullAbleVar(
//    PreferencesStoreServer(this),key,type)
//
//fun <T> SharedPreferences.saveNullAbleFlow(key:String, type:T) =  StateSavedNullAbleVar(
//    PreferencesStoreServer(this),key,type).asFlow()